package com.dhz.common.queue.guava;

import com.google.common.eventbus.AsyncEventBus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Enumeration;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author FY
 */
public class GuavaQueueManager {
    private static final Logger logger = LoggerFactory.getLogger(GuavaQueueManager.class);
    public static final ConcurrentHashMap<String, ExecutorService> GUAVA_QUEUE_EXECUTOR = new ConcurrentHashMap<String, ExecutorService>();

    /**
     * 创建一个Guava EventBus实例返回，并将应用缓存，方便在销毁时引用
     * @param threadId 线程基本ID
     * @param threadNum 线程数量
     * @return AsyncEventBus
     */
    public static AsyncEventBus createAsyncEventBus(final String threadId, final Integer threadNum) {

        assert threadId != null : "threadId must not be null!";
        assert threadNum != null : "threadId must not be null!";

        ExecutorService executor = Executors.newFixedThreadPool(threadNum);

        GUAVA_QUEUE_EXECUTOR.put(threadId, executor);

        return new AsyncEventBus(threadId, executor);
    }

    /**
     * 关闭所有的线程
     */
    public static void shutdown() {
        if (GuavaQueueManager.GUAVA_QUEUE_EXECUTOR != null) {
            Enumeration<ExecutorService> iterator = GuavaQueueManager.GUAVA_QUEUE_EXECUTOR.elements();
            while (iterator.hasMoreElements()) {
                iterator.nextElement().shutdown();
            }
        }
        logger.info("Shutdown all guava event bus thread");
    }

    /**
     * 关闭指定的线程
     * @param threadId 线程池名称
     */
    public static void shutdown(String threadId) {
        if (GuavaQueueManager.GUAVA_QUEUE_EXECUTOR != null && GuavaQueueManager.GUAVA_QUEUE_EXECUTOR.get(threadId) != null) {
            GuavaQueueManager.GUAVA_QUEUE_EXECUTOR.get(threadId).shutdown();
            logger.info("Guave Queue Server is closed, threadId is : {}", threadId);
        }
    }

}
